﻿using NPOI.OpenXmlFormats.Wordprocessing;
using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Zocono.Infrastructure.Common;
using Zocono.WCS.Domain.PlcConnectPoolDomain;

namespace Zocono.WCS.HangfireHost.TaskJobs
{
    /// <summary>
    /// 初始化PLC连接池
    /// </summary>
    public class InitPlcConnectPoolJob
    {
        private readonly IPlcConnectionPoolService _plcConnetionPoolService;
        private readonly ILogUtil _logUtil;
        private readonly TaskLock _taskLock;

        public InitPlcConnectPoolJob(IPlcConnectionPoolService plcConnetionPoolService,
            ILogUtil logUtil,
            TaskLock taskLock)
        {
            _plcConnetionPoolService = plcConnetionPoolService;
            _logUtil = logUtil;
            _taskLock = taskLock;
        }


        /// <summary>
        /// 执行任务
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public async Task DoJob(List<string> list)
        {
            if (_taskLock.InitPlcConnectTaskLock)
            {
                return;
            }
            try
            {
                _taskLock.InitPlcConnectTaskLock = true;
                await _plcConnetionPoolService.S7LoadAllPlcConnections(list);
            }
            catch (Exception ex)
            {
                _logUtil.Error($"初始化PLC连接池任务报错ex={ex}");
            }
            finally
            {
                _taskLock.InitPlcConnectTaskLock = false;
                _logUtil.Debug("初始化PLC连接池任务完成");
            }
        }

        /// <summary>
        /// 使用hangfire是调用
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public async Task HangfireJob(List<string> list)
        {
            await DoJob(list);
        }
    }
}
